package testJdk.thread.pool.scheduledExecutorServiceTest;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Description : 验证单例模式的任务对象，在线程池中的表现
 * 结论：不会顶替，而是都会执行，单例对象中变量的变化符合单例特性
 * Created by cyd on 2021-04-20 14:41:45
 */
public class SingletonTaskTest {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
        System.out.println("现在的时间：" + new Date());
        ses.schedule(MyTask01.getInstance(), 2, TimeUnit.SECONDS);
        Thread.sleep(1000);
        ses.schedule(MyTask01.getInstance(), 2, TimeUnit.SECONDS);

    }
}

class MyTask01 implements Runnable {

    public static boolean flag = false;

    private MyTask01() {

    }

    private final static MyTask01 INSTANCE = new MyTask01();

    public static MyTask01 getInstance() {
        return INSTANCE;
    }


    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        System.out.println(new Date());
        flag = !flag;
        System.out.println(flag);
    }
}
